﻿using ASmile.Com;
using ASmile.Extend;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace ASmile.Web
{
    public class UserPageAuthorizeAttribute : AuthorizeBaseAttribute
    {
        /// <summary>
        /// 默认已验证登陆权限初始化
        /// </summary>
        public UserPageAuthorizeAttribute() : this(true, true)
        { }
        /// <summary>
        /// 指定验证类型来验证登陆权限
        /// </summary>
        public UserPageAuthorizeAttribute(bool isAuth, bool isAuthRoleUrl = true)
        {
            IsAuth = isAuth;
            IsAuthRoleUrl = isAuthRoleUrl;
        }

        public UserPageAuthorizeAttribute(bool isAuth = true)
        {
            IsAuth = isAuth;
        }
        /// <summary>
        /// 登录界面的URL, 为空则跳转到配置界面
        /// </summary>
        public string LoginPageUrl { set; get; }

        protected override void AuthorizationHandle(AuthorizationFilterContext context)
        {
            if (!CheckFilter(context)) return;

            //if (!context.IsEffectivePolicy(this)) return;

            //if (!IsAuth) return;

            var token = context.HttpContext.GetToken();
            if (!LoginState.CheckToken(token, out LoginUser user))
            {
                if (LoginPageUrl.IsEmpty())
                {
                    LoginPageUrl = Config.THIS.LoginPageUrl;
                }

                //跳转至登陆页面
                context.HttpContext.Response.Redirect(LoginPageUrl);
                context.Result = new EmptyResult();
                return;
            }

            if (user.ExpiresTime - DateTime.Now < user.Expires / 2)
            {
                //如果过期时长大于token有效期的 1/2 那么刷新token，原token无效
                //token = this.HttpContext.GetToken();
                var newToken = LoginState.RefreshToken(token, out user);
                context.HttpContext.SetCookie(Config.THIS.TokenName, newToken, user.ExpiresTime);
            }
            //if (DateTime.Now > user.ExpiresTime.Add(user.Expires * -0.8))
            //{
            //    //每20%的过期时长 更新一次token
            //    var newToken = LoginState.RefreshToken(token,out _);
            //    context.HttpContext.SetCookie(Config.THIS.TokenName, newToken, user.ExpiresTime);
            //}
        }
    }
}